﻿
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Oliving.Common.LogHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Web;
namespace CotNewCommon.Base.HttpHelper
{
    /// <summary>
    /// Http数据请求类
    /// </summary>
    public static class NetHttpPost
    {

        #region 常量

        private const int ReqTimeout = 1000 * 10;

        /// <summary>
        /// 数据类型【form】
        /// </summary>
        public const string contentType_Form = "application/x-www-form-urlencoded;charset=utf-8";



        /// <summary>
        /// 数据类型【Json】
        /// </summary>
        public const string contentType_Json = "application/json;charset=utf-8";


        /// <summary>
        /// 数据类型【XML】
        /// </summary>
        public const string ContentType_XML = "text/xml;charset=utf-8";

        #endregion


        //获取 请求的结果
        public static string ToResponse(HttpWebRequest req)
        {
            string reqUri = "";
            if (req != null)
            {
                reqUri = req.RequestUri.ToString();
            }
            //      ReturnResult result = new ReturnResult();
            Stream receiveStream = null;
            HttpWebResponse wr = null;
            try
            {
                using (wr = req.GetResponse() as HttpWebResponse)
                {
                    receiveStream = wr.GetResponseStream();
                    StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
                    string content = reader.ReadToEnd();
                    return content;
                }
            }
            catch (WebException e)
            {
                wr = (HttpWebResponse)e.Response;

                if (wr == null)
                {
                    //  result = new ReturnResult() { Error = 198, Message = reqUri + "=>" + e.ToString() };
                    // return Newtonsoft.Json.JsonConvert.SerializeObject(result);
                    return "接口网络协议异常" + e.ToString();
                }
                else
                {

                    // result = new ReturnResult() { Error = (int)wr.StatusCode, Message = wr.StatusCode + "=>" + reqUri + "=>" + e.ToString() };
                    return $@"接口网络协议异常:{(int)wr.StatusCode}=>" + e.ToString(); //Newtonsoft.Json.JsonConvert.SerializeObject(result);
                }

            }
            catch (Exception e)
            {
                //result = new ReturnResult() { Error = 199, Message = reqUri + "=>" + e.ToString() };
                //return Newtonsoft.Json.JsonConvert.SerializeObject(result);
                return "接口异常" + e.ToString();
            }
            finally
            {
                //关闭连接和流
                if (wr != null)
                {
                    wr.Close();
                }
                if (req != null)
                {
                    req.Abort();
                }
            }
        }


        #region post    Form            Model

        #region MyRegion

        /// <summary>
        ///   post form 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">ＵＲＬ</param>
        /// <param name="param">参数</param>
        /// <param name="message">返回值</param>
        /// <returns></returns>
        public static T HttpPostFormToModel<T>(string url, string param, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpPostForm(url, param);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }
            return model;
        }


        /// <summary>
        /// post  Form 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">地址</param>
        /// <param name="urlParam">url参数</param>
        /// <param name="param">bity</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpPostToModel<T>(string url, string urlParam, string param, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpPostForm(url, urlParam, param);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }

            return model;
        }


        #endregion


        /// <summary>
        /// post form 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="urlParam"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpPostFormToModel<T>(string url, string urlParam, object param, ref string message) where T : new()
        {
            T model = new T();
            Type type = typeof(T);

            string strReturn = "";
            try
            {
                strReturn = HttpPostForm(url, urlParam, param);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }
            return model;
        }




        #region Base

        /// <summary>
        /// post到url,默认utf-8
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">参数</param>
        /// <returns>该url返回的数据</returns>
        public static string HttpPostForm(string url, string param)
        {
            //json数据做urlencode处理
            HttpWebRequest req;
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = contentType_Form;
            req.Timeout = ReqTimeout;
            if (!string.IsNullOrWhiteSpace(param))
            {
                byte[] postBytes = Encoding.UTF8.GetBytes(param);
                req.ContentLength = postBytes.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }
            }

            return ToResponse(req);

        }





        #endregion



        #endregion


        #region  Post  Json         Model



        /// <summary>
        /// post json 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpPostJsonToModel<T>(string url, object param, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpPostJson(url, param);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }
            return model;
        }



        /// <summary>
        /// post json 请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpPostJsonToModel<T>(string url, object param, IDictionary<string, string> Headers, ref string message) where T : new()
        {
            T model = new T();


            string strReturn = "";
            try
            {
                strReturn = HttpPostJson(url, param, Headers);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }
            return model;
        }






        #endregion


        #region HttpGet Form    Model

        /// <summary>
        /// Get Form 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpGetFormToModel<T>(string url, ref string message) where T : new()
        {
            T model = new T();
            string strReturn = "";
            try
            {
                strReturn = HttpGetForm(url);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }

            return model;
        }
        /// <summary>
        ///  get Form 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpGetFormToModel<T>(string url, string param, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpGetForm(url, param);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }
            return model;
        }



        #endregion


        #region Get Json   Model
        /// <summary>
        ///  Get Json 请求 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpGetJsonToModel<T>(string url, ref string message) where T : new()
        {
            T model = new T();
            string strReturn = "";
            try
            {
                strReturn = HttpGet(url, "", contentType_Json);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }

            return model;
        }
        /// <summary>
        ///  Get Json 请求 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpGetJsonToModel<T>(string url, string param, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpGet(url, param, contentType_Json);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }

            return model;
        }



        /// <summary>
        ///  Get Json 请求 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static T HttpGetJsonToModel<T>(string url, string param, IDictionary<string, string> Headers, ref string message) where T : new()
        {
            T model = new T();

            string strReturn = "";
            try
            {
                strReturn = HttpGet(url, param, contentType_Json, Headers);
                model = JsonConvert.DeserializeObject<T>(strReturn);
            }
            catch (Exception ex) { message = strReturn + "  -------" + ex.ToString(); }

            return model;
        }




        #endregion




        //========================================== 
        //==========================================

        #region  同步请求



        #region HttpPost  json/Form




        /// <summary>
        /// post到url,默认utf-8,application/json
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">参数</param>
        /// <returns>该url返回的数据</returns>
        public static string HttpPostJson(string url, object param, IDictionary<string, string> Headers = null)
        {
            string apiPara = "";
            //json数据做urlencode处理
            HttpWebRequest req;
            req = (HttpWebRequest)HttpWebRequest.Create(url);
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            req.Timeout = ReqTimeout;
            req.Method = "POST";
            req.ContentType = contentType_Json;
            if (Headers != null)
            {
                foreach (KeyValuePair<string, string> kvp in Headers)
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            }
            #region MyRegion

            if (param != null)
            {
                //IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                //timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                //string s = Newtonsoft.Json.JsonConvert.SerializeObject(param, Newtonsoft.Json.Formatting.Indented, timeFormat);

                var setting = new JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                };
                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

                apiPara = Newtonsoft.Json.JsonConvert.SerializeObject(param, setting);

                byte[] postBytes = Encoding.UTF8.GetBytes(apiPara);

                req.ContentLength = postBytes.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }
            }
            string apiReuslt = ToResponse(req);
            NLogger.Default.Debug("ApiPost", "url=> " + url + " 结果=》" + apiReuslt);
            // NLogger.Default.Debug("ApiPost_参数", "参数=> " + apiPara);
            return apiReuslt;

            #endregion
        }


        /// <summary>
        /// post到url,默认utf-8,application/json
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">参数</param>
        /// <returns>该url返回的数据</returns>
        public static string HttpPostJson(string url, string jsonParam, IDictionary<string, string> Headers = null)
        {
            //json数据做urlencode处理
            HttpWebRequest req;
            req = (HttpWebRequest)HttpWebRequest.Create(url);
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            req.Timeout = ReqTimeout;
            req.Method = "POST";
            req.ContentType = contentType_Json;
            if (Headers != null)
                foreach (KeyValuePair<string, string> kvp in Headers)
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }

            #region MyRegion

            if (jsonParam != null)
            {
                string s = jsonParam;
                byte[] postBytes = Encoding.UTF8.GetBytes(s);

                req.ContentLength = postBytes.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }
            }

            return ToResponse(req);


            #endregion
        }



        /// <summary>
        /// post到url,默认utf-8,application/json
        /// </summary>
        /// <param name="url">请求的URL</param>
        /// <param name="param">参数</param>
        /// <returns>该url返回的数据</returns>
        public static string HttpPostForm(string url, object param)
        {
            //json数据做urlencode处理
            HttpWebRequest req;

            req = (HttpWebRequest)HttpWebRequest.Create(url);
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            req.Timeout = ReqTimeout;
            req.Method = "POST";
            req.ContentType = contentType_Form;
            if (param != null)
            {
                string s = Newtonsoft.Json.JsonConvert.SerializeObject(param);

                byte[] postBytes = Encoding.UTF8.GetBytes(s);

                req.ContentLength = postBytes.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }
            }

            return ToResponse(req);

        }


        #endregion


        #region HttpGet Form

        /// <summary>
        /// get url,默认utf-8
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string HttpGetForm(string url)
        {
            WebResponse response = null;
            //json数据做urlencode处理
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Timeout = ReqTimeout;
            request.ContentType = contentType_Form;
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }


            return ToResponse(request);

        }


        /// <summary>
        /// get url,默认utf-8
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string HttpGetForm(string url, string param)
        {
            return HttpGet(url, param, contentType_Form);
        }


        /// <summary>
        /// Get Json
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string HttpGetJson(string url, string param)
        {
            return HttpGet(url, param, contentType_Json);
        }

        public static string HttpGetJson(string url, string param, IDictionary<string, string> Headers)
        {
            return HttpGet(url, param, contentType_Json, Headers);
        }



        public static string HttpGetJson(string url)
        {
            WebResponse response = null;
            //json数据做urlencode处理
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.Timeout = ReqTimeout;
            request.ContentType = contentType_Json;
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            return ToResponse(request);

        }


        public static string HttpGetJson(string url, IDictionary<string, string> Headers)
        {
            WebResponse response = null;
            //json数据做urlencode处理
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = contentType_Json;
            request.Timeout = ReqTimeout;

            if (Headers != null)
                foreach (KeyValuePair<string, string> kvp in Headers)
                {
                    request.Headers.Add(kvp.Key, kvp.Value);
                }
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            return ToResponse(request);


        }


        #endregion


        #region PostXML

        public static string PostXML(string xml, string url)
        {
            return PostXML(xml, url, 6);
        }
        public static string PostXML(string xml, string url, int timeout)
        {
            return PostXML(xml, url, false, "", "", timeout);
        }
        public static string PostXML(string xml, string url, bool isUseCert, string SSLCERT_PATH, string SSLCERT_PASSWORD, int timeout)
        {
            //System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接

            string result = "";//返回结果

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;

            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "POST";
                request.Timeout = timeout * 1000;

                //设置代理服务器
                //WebProxy proxy = new WebProxy();                          //定义一个网关对象
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //网关服务器端口:端口
                //request.Proxy = proxy;

                //设置POST的数据类型和长度
                request.ContentType = ContentType_XML;
                byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
                request.ContentLength = data.Length;

                //是否使用证书
                if (isUseCert)
                {
                    string path = HttpContext.Current.Request.PhysicalApplicationPath;
                    X509Certificate2 cert = new X509Certificate2(path + SSLCERT_PATH, SSLCERT_PASSWORD);
                    request.ClientCertificates.Add(cert);
                }

                //往服务器写入数据
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();

                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                System.Threading.Thread.ResetAbort();

                return e.Message.ToString();
            }
            catch (WebException e)
            {
                return e.Message.ToString();
            }
            catch (Exception e)
            {
                return e.Message.ToString();
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }


        #endregion


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }




        #endregion


        //==========================================

        #region 注释


        #endregion

        #region File

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="name">文件参数名（相当于form表单中选择文件input的name）</param>
        /// <param name="filePath">文件地址</param>
        /// <returns></returns>
        public static string HttpUploadFile(string url, string name, string filePath)
        {
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            //判断文件是否存在
            if (!File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            string result;

            //这种方式没法给file name 命名
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;  
            //WebClient myWebClient = new WebClient();
            //myWebClient.Credentials = CredentialCache.DefaultCredentials;
            //try
            //{
            //    byte[] responseArray = myWebClient.UploadFile(url, "POST",media);
            //    result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length); 
            //}
            //catch (Exception ex)
            //{
            //    result = "Error:" + ex.Message;
            //} 
            //return result;

            //构造数据包前半段 
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;

            var stream = request.GetRequestStream();
            stream.Write(boundarybytes, 0, boundarybytes.Length);
            //将文件写进流
            var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            var header = string.Format(headerTemplate, name, filePath.Substring(filePath.LastIndexOf('\\') + 1), GetContentType(new FileInfo(filePath)));
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);

            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            var buffer = new byte[4096];
            var bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }

            //封闭数据包并发送
            var trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);

            fileStream.Dispose();
            fileStream.Close();
            stream.Dispose();
            stream.Close();

            //发送并显示返回结果
            WebResponse wresp = null;
            Stream stream2 = null;
            StreamReader reader2 = null;
            try
            {
                wresp = request.GetResponse();

                stream2 = wresp.GetResponseStream();
                reader2 = new StreamReader(stream2);
                result = reader2.ReadToEnd();
            }
            finally
            {

                if (stream2 != null)
                {
                    stream2.Dispose();
                    stream2.Close();
                }
                if (reader2 != null)
                {
                    reader2.Dispose();
                    reader2.Close();
                }
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }

            return result;
        }

        public static string HttpUploadFile(string url, string name, FileInfo file)
        {
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            string result;
            //构造数据包前半段 
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;

            var stream = request.GetRequestStream();
            stream.Write(boundarybytes, 0, boundarybytes.Length);


            //将文件写进流
            var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            var header = string.Format(headerTemplate, name, name, GetContentType(file));
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);


            FileStream fileStream = file.Open(FileMode.Open, FileAccess.Read);
            //new FileStream(filePath, FileMode.Open, FileAccess.Read);

            var buffer = new byte[4096];
            var bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();




            //封闭数据包并发送
            var trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);

            fileStream.Dispose();
            fileStream.Close();
            stream.Dispose();
            stream.Close();

            //发送并显示返回结果
            WebResponse wresp = null;
            Stream stream2 = null;
            StreamReader reader2 = null;
            try
            {
                wresp = request.GetResponse();

                stream2 = wresp.GetResponseStream();
                reader2 = new StreamReader(stream2);

                result = reader2.ReadToEnd();
            }
            finally
            {
                if (stream2 != null)
                {
                    stream2.Dispose();
                    stream2.Close();
                }
                if (reader2 != null)
                {
                    reader2.Dispose();
                    reader2.Close();
                }
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }

            return result;
        }


        public static string HttpUploadFile(string url, string name, List<FileInfo> files)
        {
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            string result;
            //构造数据包前半段 
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;

            var stream = request.GetRequestStream();
            stream.Write(boundarybytes, 0, boundarybytes.Length);

            foreach (FileInfo file in files)
            {
                //将文件写进流
                var headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                var header = string.Format(headerTemplate, file.Name, file.Name, GetContentType(file));
                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                stream.Write(headerbytes, 0, headerbytes.Length);


                FileStream fileStream = file.Open(FileMode.Open, FileAccess.Read);
                //new FileStream(filePath, FileMode.Open, FileAccess.Read);

                var buffer = new byte[4096];
                var bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
                fileStream.Dispose();
                fileStream.Close();

            }


            //封闭数据包并发送
            var trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);
            stream.Dispose();
            stream.Close();
            //发送并显示返回结果
            WebResponse wresp = null;
            Stream stream2 = null;
            StreamReader reader2 = null;
            try
            {
                wresp = request.GetResponse();

                stream2 = wresp.GetResponseStream();
                reader2 = new StreamReader(stream2);

                result = reader2.ReadToEnd();
            }
            finally
            {
                if (stream2 != null)
                {
                    stream2.Dispose();
                    stream2.Close();
                }
                if (reader2 != null)
                {
                    reader2.Dispose();
                    reader2.Close();
                }
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }

            return result;
        }




        /// <summary>
        /// 通过Post请求下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="path">保存路径</param>
        /// <returns></returns>
        public static string HttpPostLoadFile(string url, object param, string path)
        {
            //json数据做urlencode处理
            HttpWebRequest req;

            req = (HttpWebRequest)HttpWebRequest.Create(url);
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            if (param != null)
            {
                string s = Newtonsoft.Json.JsonConvert.SerializeObject(param);

                byte[] postBytes = Encoding.UTF8.GetBytes(s);

                req.Method = "POST";
                req.ContentType = contentType_Json;
                req.ContentLength = postBytes.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }
            }
            Stream receiveStream = null;
            FileStream fs = null;
            HttpWebResponse wr = null;
            try
            {
                using (wr = req.GetResponse() as HttpWebResponse)
                {
                    //StreamReader reader = new StreamReader(receiveStream);
                    //string content = reader.ReadToEnd();

                    receiveStream = wr.GetResponseStream();
                    fs = new FileStream(path, FileMode.Create);

                    byte[] nbytes = new byte[512];
                    int nReadSize = 0;
                    nReadSize = receiveStream.Read(nbytes, 0, 512);
                    while (nReadSize > 0)
                    {
                        fs.Write(nbytes, 0, nReadSize);
                        nReadSize = receiveStream.Read(nbytes, 0, 512);
                    }
                }
                return path;
            }
            catch (WebException e)
            {
                return e.Message.ToString();
            }
            finally
            {
                fs.Dispose();
                fs.Close();
                receiveStream.Dispose();
                receiveStream.Close();
                wr.Close();
            }

            //WebClient myWebClient = new WebClient();  
            //try
            //{ 
            //    byte[] responseArray = myWebClient.DownloadFile(
            //    result = System.Text.Encoding.Default.GetString(responseArray, 0, responseArray.Length);
            //    //WriteLog("上传result:" + result);
            //    //UploadMM _mode = JsonHelper.ParseFromJson<UploadMM>(result);
            //    //result = _mode.media_id;
            //}
            //catch (Exception ex)
            //{
            //    result = "Error:" + ex.Message;
            //}
        }


        /// <summary>
        /// 通过Get请求下载文件
        /// </summary>
        /// <param name="url"></param> 
        /// <param name="path">保存路径</param>
        /// <returns></returns>
        public static string HttpGetLoadFile(string url, string path)
        {
            //json数据做urlencode处理
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            req.Method = "GET";

            Stream receiveStream = null;
            FileStream fs = null;
            HttpWebResponse wr = null;
            try
            {
                using (wr = req.GetResponse() as HttpWebResponse)
                {
                    //if (wr.Headers["Content-disposition"]!=null)
                    //{
                    //    //wr.Headers["Content-disposition"]	"attachment; filename=\"O3Qo1l9mQz9BMVl11hdKvQEtXc32jHrLbDBvlbNCqeXWGZjYuS4XQY2gw-Y14SHv.jpg\""	 
                    //    string filename = wr.Headers["Content-disposition"]; 
                    //}
                    receiveStream = wr.GetResponseStream();
                    fs = new FileStream(path, FileMode.OpenOrCreate);

                    byte[] nbytes = new byte[512];
                    int nReadSize = 0;
                    nReadSize = receiveStream.Read(nbytes, 0, 512);
                    while (nReadSize > 0)
                    {
                        fs.Write(nbytes, 0, nReadSize);
                        nReadSize = receiveStream.Read(nbytes, 0, 512);
                    }
                }

                return path;
            }
            catch (WebException e)
            {
                return e.Message.ToString();
            }
            finally
            {
                fs.Dispose();
                fs.Close();
                receiveStream.Dispose();
                receiveStream.Close();
                wr.Close();
            }
        }
        /// <summary>
        /// 获取文件类型
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        private static string GetContentType(FileInfo fileInfo)
        {
            var contentType = "";
            switch (fileInfo.Extension.ToLower())
            {
                case ".jpg":
                case ".png":
                case ".gif":
                case ".bmp":
                    contentType = "image/jpeg";
                    break;
                case ".mp3":
                    contentType = "audio/mp3";
                    break;
                case ".amr":
                    contentType = "audio/amr";
                    break;
                case ".mp4":
                    contentType = "video/mp4";
                    break;
                default:
                    throw new NotSupportedException("文件格式不支持");
            }

            return contentType;
        }



        #endregion


        #region 异步请求
        public class RequestState
        {
            const int BufferSize = 1024;
            public StringBuilder RequestData;
            public byte[] BufferRead;
            public WebRequest Request;
            public Stream ResponseStream;
            // Create Decoder for appropriate enconding type.
            public Decoder StreamDecode = Encoding.UTF8.GetDecoder();

            public RequestState()
            {
                BufferRead = new byte[BufferSize];
                RequestData = new StringBuilder(String.Empty);
                Request = null;
                ResponseStream = null;
            }
        }

        // ClientGetAsync issues the async request.
        class ClientGetAsync
        {
            public static ManualResetEvent allDone = new ManualResetEvent(false);
            const int BUFFER_SIZE = 1024;

            public static void Main(string[] args)
            {
                if (args.Length < 1)
                {
                    showusage();
                    return;
                }

                // Get the URI from the command line.
                Uri httpSite = new Uri(args[0]);

                // Create the request object.
                WebRequest wreq = WebRequest.Create(httpSite);

                // Create the state object.
                RequestState rs = new RequestState();

                // Put the request into the state object so it can be passed around.
                rs.Request = wreq;

                // Issue the async request.
                IAsyncResult r = (IAsyncResult)wreq.BeginGetResponse(
                   new AsyncCallback(RespCallback), rs);

                // Wait until the ManualResetEvent is set so that the application 
                // does not exit until after the callback is called.
                allDone.WaitOne();

                Console.WriteLine(rs.RequestData.ToString());
            }

            public static void showusage()
            {
                Console.WriteLine("Attempts to GET a URL");
                Console.WriteLine(" Usage:");
                Console.WriteLine("   ClientGetAsync URL");
                Console.WriteLine("   Example:");
                Console.WriteLine("      ClientGetAsync http://www.contoso.com/");
            }

            private static void RespCallback(IAsyncResult ar)
            {
                // Get the RequestState object from the async result.
                RequestState rs = (RequestState)ar.AsyncState;

                // Get the WebRequest from RequestState.
                WebRequest req = rs.Request;

                // Call EndGetResponse, which produces the WebResponse object
                //  that came from the request issued above.
                WebResponse resp = req.EndGetResponse(ar);

                //  Start reading data from the response stream.
                Stream ResponseStream = resp.GetResponseStream();

                // Store the response stream in RequestState to read 
                // the stream asynchronously.
                rs.ResponseStream = ResponseStream;

                //  Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead
                IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0,
                   BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
            }


            private static void ReadCallBack(IAsyncResult asyncResult)
            {
                // Get the RequestState object from AsyncResult.
                RequestState rs = (RequestState)asyncResult.AsyncState;

                // Retrieve the ResponseStream that was set in RespCallback. 
                Stream responseStream = rs.ResponseStream;

                // Read rs.BufferRead to verify that it contains data. 
                int read = responseStream.EndRead(asyncResult);
                if (read > 0)
                {
                    // Prepare a Char array buffer for converting to Unicode.
                    Char[] charBuffer = new Char[BUFFER_SIZE];

                    // Convert byte stream to Char array and then to String.
                    // len contains the number of characters converted to Unicode.
                    int len =
                       rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);

                    String str = new String(charBuffer, 0, len);

                    // Append the recently read data to the RequestData stringbuilder
                    // object contained in RequestState.
                    rs.RequestData.Append(
                       Encoding.ASCII.GetString(rs.BufferRead, 0, read));

                    // Continue reading data until 
                    // responseStream.EndRead returns –1.
                    IAsyncResult ar = responseStream.BeginRead(
                       rs.BufferRead, 0, BUFFER_SIZE,
                       new AsyncCallback(ReadCallBack), rs);
                }
                else
                {
                    if (rs.RequestData.Length > 0)
                    {
                        //  Display data to the console.
                        string strContent;
                        strContent = rs.RequestData.ToString();
                    }
                    // Close down the response stream.
                    responseStream.Close();
                    // Set the ManualResetEvent so the main thread can exit.
                    allDone.Set();
                }
                return;
            }
        }
        #endregion





        public static string HttpPostForm(string url, string urlParam, string param, IDictionary<string, string> Headers = null)
        {
            return HttpPost(url + (url.EndsWith("?") ? "" : "?") + urlParam, param, "post", Encoding.UTF8, contentType_Form, Headers);
        }

        public static string HttpPostForm(string url, string urlParam, object param, IDictionary<string, string> Headers = null)
        {
            return HttpPost(url, urlParam, param, contentType_Form, Headers);
        }

        /// <summary>
        /// post 请求   ggg 
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="urlParam">参数</param>
        /// <param name="param">文件数据</param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string urlParam, object param, string contentType, IDictionary<string, string> Headers = null)
        {
            #region 对象转字符串参数
            StringBuilder sb = new StringBuilder();
            if (param != null)
            {
                Type type1 = param.GetType();
                System.Reflection.PropertyInfo[] fields1 = type1.GetProperties();

                foreach (System.Reflection.PropertyInfo field1 in fields1)
                {
                    string name1 = field1.Name;
                    System.Reflection.PropertyInfo pi1 = type1.GetProperty(name1);
                    object s1 = pi1.GetValue(param, null);
                    if (s1 != null)
                        sb.Append(name1 + "=" + s1.ToString() + "&");
                }
            }
            #endregion
            return HttpPost(url + (url.EndsWith("?") ? "" : "?") + urlParam, sb.ToString().TrimEnd('&'), "post", Encoding.UTF8, contentType, Headers);
        }


        #region Base
        /// <summary>
        /// post到url  【Base】
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <param name="method">发送方式 GET，POST</param>
        /// <returns></returns>
        public static string HttpPost(string url, string param, string method, Encoding encoding, string contentType, IDictionary<string, string> Headers)
        {
            HttpWebRequest req;
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            req = (HttpWebRequest)HttpWebRequest.Create(url);
            byte[] postBytes = encoding.GetBytes(param);
            req.Method = method;
            req.Timeout = ReqTimeout;
            req.ContentType = contentType;
            req.ContentLength = postBytes.Length;
            if (Headers != null)
                foreach (KeyValuePair<string, string> kvp in Headers)
                {
                    req.Headers.Add(kvp.Key, kvp.Value);
                }
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(postBytes, 0, postBytes.Length);
            }


            return ToResponse(req);

        }


        /// <summary>
        /// post数据
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="values">数据键值对</param>  
        /// <param name="contentType">Content-typeHttp标头值</param> 
        /// <returns></returns>
        public static string HttpPost(string url, NameValueCollection values, string contentType)
        {
            return HttpPost(url, values, Encoding.UTF8, contentType, null);
        }


        /// <summary>
        /// post数据
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="values">数据键值对</param> 
        /// <param name="encoding">编码</param>
        /// <param name="contentType">Content-typeHttp标头值</param>
        /// <param name="Headers">标头的键值对集合</param>
        /// <returns></returns>
        public static string HttpPost(string url, NameValueCollection values, Encoding encoding, string contentType, NameValueCollection Headers)
        {
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            HttpWebRequest req;
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            req = (HttpWebRequest)HttpWebRequest.Create(url);
            //提交文本字段
            if (values != null)
            {
                byte[] line = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                using (Stream reqStream = req.GetRequestStream())
                {
                    string format = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
                    foreach (string key in values.Keys)
                    {
                        string s = string.Format(format, key, values[key]);
                        byte[] data = Encoding.UTF8.GetBytes(s);
                        reqStream.Write(data, 0, data.Length);
                    }
                    reqStream.Write(line, 0, line.Length);
                    req.ContentLength = reqStream.Length;
                }
            }
            req.Method = "POST";
            req.ContentType = contentType;
            req.Timeout = ReqTimeout;
            foreach (KeyValuePair<string, string> kvp in Headers)
            {
                req.Headers.Add(kvp.Key, kvp.Value);
            }


            return ToResponse(req);

        }



        #endregion




        /// <summary>
        /// 对象转字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns></returns>
        public static string GetParamByObject(object o)
        {
            ArrayList arrValue = new ArrayList();
            System.Reflection.PropertyInfo[] p = o.GetType().GetProperties();
            foreach (System.Reflection.PropertyInfo pi in p)
            {
                arrValue.Add(pi.Name + "=" + pi.GetValue(o, null));
            }

            //ArrarList 转换为 string[]
            string[] objPName = (string[])arrValue.ToArray(typeof(string));

            return string.Join("&", objPName);
        }


        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url">地址</param> 
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            return HttpGet(url, "", contentType_Form);
        }

        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="param">ＵＲＬ参数</param>
        /// <param name="contentType">数据类型</param>
        /// <returns></returns>
        public static string HttpGet(string url, string param, string contentType)
        {
            WebResponse response = null;
            //json数据做urlencode处理
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + (url.Contains('?') ? "&" : url.EndsWith("?") ? "" : "?") + param.TrimStart('?'));
            request.Method = "Get";
            request.Timeout = ReqTimeout;
            request.ContentType = contentType;
            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            return ToResponse(request);

        }


        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="param">ＵＲＬ参数</param>
        /// <param name="contentType">数据类型</param>
        /// <returns></returns>
        public static string HttpGet(string url, string param, string contentType, IDictionary<string, string> Headers)
        {
            WebResponse response = null;
            //json数据做urlencode处理
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + (url.Contains('?') ? "&" : url.EndsWith("?") ? "" : "?") + param.TrimStart('?'));
            request.Method = "Get";
            request.ContentType = contentType;
            request.Timeout = ReqTimeout;

            if (Headers != null)
                foreach (KeyValuePair<string, string> kvp in Headers)
                {
                    request.Headers.Add(kvp.Key, kvp.Value);
                }


            if (url.StartsWith("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            return ToResponse(request);


        }


    }




    #region 通用辅助类。可发https请求
    /// <summary>   
    /// 有关HTTP请求的辅助类   
    /// </summary>   
    public class HttpWebResponseUtility
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        /// <summary>   
        /// 创建GET方式的HTTP请求   
        /// </summary>   
        /// <param name="url">请求的URL</param>   
        /// <param name="timeout">请求的超时时间</param>   
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>   
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>   
        /// <returns></returns>   
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = DefaultUserAgent;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            return request.GetResponse() as HttpWebResponse;
        }
        /// <summary>   
        /// 创建POST方式的HTTP请求   
        /// </summary>   
        /// <param name="url">请求的URL</param>   
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>   
        /// <param name="timeout">请求的超时时间</param>   
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>   
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>   
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>   
        /// <returns></returns>   
        public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (requestEncoding == null)
            {
                throw new ArgumentNullException("requestEncoding");
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求   
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }

            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //如果需要POST数据   
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = requestEncoding.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            return request.GetResponse() as HttpWebResponse;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受   
        }
    }

    #endregion





}